#!/usr/bin/env python
# -*- coding: UTF-8 -*-

try:
	import pdb
	import pygame
	import sys
	from battlefield import Battlefield
	from command import Command
	from creature import Creature
	from cursor import Cursor
	from menu import *
	from pygame.locals import *
	from utils import *
except ImportError, err:
	print "Could not load %s module." % (err)
	raise SystemExit

class ScenarioDef(object):
	def __init__(self):
		object.__init__(self)
		self.field_filename = 'scenario18.png'
		self.cursor_start = [0,0] # not yet used


class Scenario(object):
	def __init__(self):
		object.__init__(self)

		self.MOVEMENT_KEYS = (str(K_UP), str(K_RIGHT), str(K_DOWN), str(K_LEFT))
		self.CANCEL_KEYS = (str(K_BACKSPACE))
		self.ACTION_KEYS = (str(K_RETURN))

		self.clock = pygame.time.Clock()
		self.scen_data = ScenarioDef()
		self.animating = 0

		# init screen
		pygame.init()
		pygame.key.set_repeat(300, 100)
		#self.screen = pygame.display.set_mode((768, 576))
		self.screen = pygame.display.set_mode((800, 600))
		self.field = Battlefield(self, self.scen_data.field_filename)

		# init layers (map, creatures, other, cursor)
		self.layers = {}
		self.layers[0] = pygame.sprite.RenderPlain(self.field)
		self.layers[1] = pygame.sprite.RenderPlain(Creature())
		self.layers[2] = pygame.sprite.RenderPlain()
		self.layers[3] = pygame.sprite.RenderPlain()

		self.cursor = Cursor(self.layers[3])
		self.command = None
		self.window = None

	def run(self):
		while 1:
			for event in pygame.event.get():
				try:
					if event.type == QUIT:
						pygame.quit()
						return
					elif event.type == USEREVENT:
						if event.name == 'ANIM_END':
							self.animating = 0
							continue
						elif event.name == 'WINDOW_CLOSED':
							self.finish_window_close()
							continue
					elif self.animating:
						# ignore the event
						continue
					elif event.type == KEYDOWN:
						if event.key == K_ESCAPE:
							pygame.quit()
							return
						if str(event.key) in self.CANCEL_KEYS:
							self.do_cancel()
						elif str(event.key) in self.MOVEMENT_KEYS:
							self.do_movement(event.key)
						elif str(event.key) in self.ACTION_KEYS:
							self.do_action()

				except Exception:
					print sys.exc_info()

			self.layers[0].update()
			self.layers[1].update()
			self.layers[2].update()
			self.layers[3].update()

			# of course, layers can be reordered by simply shuffling
			# around the following 4 statements
			self.layers[0].draw(self.screen)
			self.layers[1].draw(self.screen)
			self.layers[2].draw(self.screen)
			self.layers[3].draw(self.screen)
			pygame.display.flip()
			self.clock.tick(60)


	def do_cancel(self):
		if self.command:
			self.command.kill()
			self.window = self.command.parent_window
			self.window.show()
			self.animating = self.window.open()
			self.command = None
		elif self.window:
			# start window close
			self.animating = self.window.close()

	def finish_window_close(self):
		# called on USEREVENT WINDOW_CLOSED
		self.animating = 0
		self.window.kill()
		self.window = self.window.parent_window
		if not self.window: self.cursor.show()


	def do_movement(self, key):
		if self.command:
			self.command.move(key)
		elif self.window:
			self.window.move_cursor(key)
		else:
			self.animating = self.cursor.move(key) \
						or self.field.r_move(key) \
						and [s.r_move(key) for s in self.layers[1]]


	def do_action(self):
		if self.command:
			self.command.execute(self.target)
			self.command.kill()
			self.command = None
			self.window.kill()
			self.window = None
		elif self.window:
			self.command = self.window.do_action()
			# do_action() returns new Command or Window
			# remember to set parent_window
			if isinstance(self.command, Command):
				self.window.hide()
			else:
				# command is actually another window
				self.window = self.command
				self.command = None
				self.animating = self.window.open()
			self.field.colorize(1, 1)
		else:
			creature = [c for c in self.layers[1] \
					if self.cursor.rect.contains(c.rect)]
			if len(creature):
				self.window = CreatureMenu(self.layers, iter(creature).next())
			else:
				self.window = SystemMenu(self.layers)
			self.animating = self.window.open()
			self.cursor.hide()

